package cn.amaake.magicplugin.nacos.service;

import cn.amaake.magicplugin.nacos.config.NacosConfig;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.ssssssss.magicapi.core.config.MagicAPIProperties;

import java.util.Properties;

public class NacosDiscovery {

    private static final Logger logger = LoggerFactory.getLogger(NacosDiscovery.class);

    /**
     * 当前服务的端口
     */
    private int serverPort;

    /**
     * 当前服务的名称
     */
    private String appName;

    private MagicAPIProperties properties;
    private NacosConfig nacosConfig;

    private ApplicationContext applicationContext;

    private NamingService namingService;

    public NamingService getNamingService() {
        return namingService;
    }

    public NacosDiscovery(MagicAPIProperties properties, NacosConfig nacosConfig, ApplicationContext applicationContext) throws NacosException {
        this.properties = properties;
        this.nacosConfig = nacosConfig;
        this.applicationContext = applicationContext;
        Environment env = applicationContext.getEnvironment();
        serverPort = Integer.parseInt(env.getProperty("server.port"));
        appName = env.getProperty("spring.application.name");
        //init();
    }



    @PostConstruct
    private void init() throws NacosException {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosConfig.getServerAddr());
        if (nacosConfig.isEnabledAuth()){
            properties.setProperty(PropertyKeyConst.USERNAME,nacosConfig.getUsername());
            properties.setProperty(PropertyKeyConst.PASSWORD,nacosConfig.getPassword());
        }
        if(StrUtil.isNotEmpty(nacosConfig.getNamespace())){
            properties.setProperty(PropertyKeyConst.NAMESPACE, nacosConfig.getNamespace());
        }
        //namingService = NamingFactory.createNamingService(nacosConfig.getServerAddr());
        namingService = NamingFactory.createNamingService(properties);
        if (StrUtil.hasEmpty(nacosConfig.getIp())){
            nacosConfig.setIp(NetUtil.getLocalhostStr());
        }
        if(StrUtil.hasEmpty(nacosConfig.getClusterName())){
            namingService.registerInstance(appName,nacosConfig.getGroup(), nacosConfig.getIp(), serverPort);
        }else{
            namingService.registerInstance(appName,nacosConfig.getGroup(), nacosConfig.getIp(), serverPort, nacosConfig.getClusterName());
        }
    }
}
